package cn.francis.service.impl;

import cn.francis.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.agro.common.ResultInfo;
import com.qfedu.agro.util.JwtUtil;
import com.qfedu.agro.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Name: UserServiceImpl
 * Package: cn.francis.service.impl
 * Date: 2024/10/24 - 10:18
 * Description:
 *
 * @author Junhui Zhang
 * @version v1.0
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResultInfo login(String username, String password) {
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate == null) {
            return ResultInfo.error("登录失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        String json = null;
        try {
            json = new ObjectMapper().writeValueAsString(loginUser);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("登陆失败");
        }
        redisTemplate.opsForValue().set("login:" + loginUser.getSysUser().getId(), json, 60 * 30, TimeUnit.SECONDS);

        JwtUtil jwtUtil = new JwtUtil();
        String jwtToken = jwtUtil.createJWT(String.valueOf(loginUser.getSysUser().getId()), loginUser.getSysUser().getUsername(), null);
        return ResultInfo.success(jwtToken);
    }

    @Override
    public ResultInfo logout() {
        // 删除redis缓存信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisTemplate.delete("login:" + loginUser.getSysUser().getId());
        // 删除容器中的认证信息
        SecurityContextHolder.clearContext();
        return ResultInfo.success(null);
    }
}
